#include <iostream>
#include <fcntl.h>
#include <unistd.h>

void SetNonBlock(int fd)
{
    int fl = fcntl(fd, F_GETFL);
    if(fl < 0)
    {
        printf("fcntl出错\n");
        return;
    }

    fcntl(fd, F_SETFL, fl | O_NONBLOCK);
}

void TestNonBlock()
{
    char buffer[1024];
    SetNonBlock(0);

    while(true)
    {
        ssize_t s = read(0, buffer, sizeof(buffer) - 1);
        if(s > 0)
        {
            buffer[s] = '\0';
            std::cout << "echo# " << buffer << std::endl;
        }
        else if(errno == EWOULDBLOCK || errno == EAGAIN) // 表示被阻塞
        {
            printf("非阻塞做其他事\n");
        }
        else if(errno == EINTR)
        {
            // 被信号中断
            continue;
        }
        else 
        {
            printf("读取错误\n");
            
        }
        sleep(1);
    }
}

int main()
{
    TestNonBlock();
    return 0;
}